//
//  SmallDecisionsVipViewController.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/8/13.
//

#import "SmallDecisionsVipViewController.h"
#import "SmallDecisionsWebViewController.h"
#import "SmallDecisionsIAPHelper.h"

@interface SmallDecisionsVipCell : UICollectionViewCell

@property(nonatomic, strong) NSDictionary *data;
@property(nonatomic, assign) BOOL isSelected;

@end

@interface SmallDecisionsVipCell()

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *moneyLabel;
@property (nonatomic, strong) UILabel *tipLabel;

@end

@implementation SmallDecisionsVipCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.contentView.backgroundColor = SmallDecisionsBgColor;
        self.backgroundColor = SmallDecisionsBgColor;
        self.layer.cornerRadius = 8;
        self.layer.masksToBounds = YES;
        self.layer.borderWidth = 2.5;
        [self createSmallDecisionsVipCellSubviews];
    }
    return self;
}

- (void)createSmallDecisionsVipCellSubviews {
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.font = SmallDecisionsSetFontSize(18);
    nameLabel.textColor = SmallDecisionsThemeFontColor;
    [self.contentView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(32);
        make.centerX.mas_equalTo(self.contentView);
    }];
    self.nameLabel = nameLabel;

    UILabel *moneyLabel = [[UILabel alloc] init];
    moneyLabel.font = SmallDecisionsSetFontSize(16);
    moneyLabel.textColor = SmallDecisionsThemeFontColor;
    [self.contentView addSubview:moneyLabel];
    [moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameLabel.mas_bottom).offset(22);
        make.centerX.mas_equalTo(self.contentView);
    }];
    self.moneyLabel = moneyLabel;

    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.font = SmallDecisionsSetFontSize(14);
    tipLabel.textColor = SmallDecisionsLineHeightColor;
    [self.contentView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.contentView);
        make.bottom.equalTo(self.contentView.mas_bottom).offset(-10);
    }];
    self.tipLabel = tipLabel;
}

- (void)setData:(NSDictionary *)data {
    _data = data;
    self.nameLabel.text = data[@"name"];
    self.moneyLabel.text = [NSString stringWithFormat:@"%@",data[@"money"]];
    self.tipLabel.text = data[@"message"];
}

- (void)setIsSelected:(BOOL)isSelected {
    _isSelected = isSelected;
    if(isSelected) {
        self.layer.borderColor = SmallDecisionsThemeColor.CGColor;
    } else {
        self.layer.borderColor = SmallDecisionsBgColor.CGColor;
    }
}

@end

@interface SmallDecisionsVipViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UIScrollView *containerScrollView;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSArray *vipItems;
@property (nonatomic,assign) NSUInteger vipItemCheckedIndex;
@property (nonatomic,strong) UIView *bottomMaskView;
@end

@implementation SmallDecisionsVipViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.vipItemCheckedIndex = 0;
        [self setDefaultVipItems];
    }
    return self;
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    CGRect bottomMaskViewReact = self.bottomMaskView.bounds;
    // 绘制圆角 需设置的圆角 使用"|"来组合
    UIBezierPath *maskBezierPath = [UIBezierPath bezierPathWithRoundedRect:bottomMaskViewReact byRoundingCorners:UIRectCornerTopLeft |
    UIRectCornerTopRight cornerRadii:CGSizeMake(32, 32)];
    CAShapeLayer *maskShapeLayer = [[CAShapeLayer alloc]init];
    // 设置大小
    maskShapeLayer.frame = bottomMaskViewReact;
    // 设置图形样子
    maskShapeLayer.path = maskBezierPath.CGPath;
    self.bottomMaskView.layer.mask = maskShapeLayer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"VIP会员";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self createSmallDecisionsVipVCSubviews];
    if(self.showLeftClose) {
        [self setLeftBarButtonItemCloseButton];
    }
}

- (void)setDefaultVipItems {
    self.vipItems = @[
        @{
            @"name":@"年会员",
            @"money":@"¥ 168",
            @"productId":@"com.hipart.luckyYear",
        }, @{
            @"name":@"季会员",
            @"money":@"¥ 68",
            @"productId":@"com.hipart.luckyQuarter",
        }, @{
            @"name":@"月会员",
            @"money":@"¥ 28",
            @"productId":@"com.hipart.luckMonth",
        }
    ];
}

- (void)createSmallDecisionsVipVCSubviews {
    UIImageView *introImageView = [[UIImageView alloc] init];
    [introImageView setImage:[UIImage imageNamed:@"vip_intro_img"]];
    [self.containerScrollView addSubview:introImageView];
    [introImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(10);
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.height.mas_offset(kScreenWidth * 0.32);
    }];

    NSArray *imageNames1 = @[@"vip_intro_tag_img1",@"vip_intro_tag_img2"];
    NSMutableArray *mutImages1 = [NSMutableArray array];
    for (NSInteger i = 0,n = imageNames1.count; i < n; i ++ ) {
        UIImageView *vipTagImageView = [[UIImageView alloc] init];
        vipTagImageView.image = [UIImage imageNamed:imageNames1[i]];
        [self.view addSubview:vipTagImageView];
        [mutImages1 addObject:vipTagImageView];
    }

    [mutImages1 mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:20 leadSpacing:10 tailSpacing:10];
    [mutImages1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(introImageView.mas_bottom).offset(-10);
        make.height.mas_offset(80);
    }];


    NSArray *imageNames2 = @[@"vip_intro_tag_img3",@"vip_intro_tag_img4"];
    NSMutableArray *mutImages2 = [NSMutableArray array];
    for (NSInteger i = 0,n = imageNames2.count; i < n; i ++ ) {
        UIImageView *vipTagImageView = [[UIImageView alloc] init];
        vipTagImageView.image = [UIImage imageNamed:imageNames2[i]];
        [self.view addSubview:vipTagImageView];
        [mutImages2 addObject:vipTagImageView];
    }

    [mutImages2 mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:20 leadSpacing:10 tailSpacing:10];
    [mutImages2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(introImageView.mas_bottom).offset(80);
        make.height.mas_offset(80);
    }];

    [self.bottomMaskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(introImageView.mas_bottom).offset(182);
        make.left.right.equalTo(self.view);
        make.height.lessThanOrEqualTo(self.view);
    }];


    UILabel *introVipLabel = [[UILabel alloc] init];
    introVipLabel.font = SmallDecisionsSetBoldFontSize(16);
    introVipLabel.textColor = SmallDecisionsThemeFontColor;
    introVipLabel.text = @"VIP项目类型";
    [self.bottomMaskView addSubview:introVipLabel];
    [introVipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
    }];

    [self.bottomMaskView addSubview:self.collectionView];

    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(introVipLabel.mas_bottom).offset(20);
        make.height.mas_offset(142);
        make.left.right.mas_offset(0);
    }];

    UIButton *openVipBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    openVipBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(16);
    openVipBtn.backgroundColor = SmallDecisionsThemeColor;
    openVipBtn.layer.cornerRadius = 26;
    openVipBtn.layer.masksToBounds = YES;
    [openVipBtn setTitle:@"立即开通" forState:UIControlStateNormal];
    [openVipBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
    [openVipBtn addTarget:self action:@selector(openVipBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:openVipBtn];

    [openVipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).offset(30);
        make.left.right.equalTo(introImageView);
        make.height.mas_offset(58);
    }];


    UILabel *remindLabel = [[UILabel alloc] init];
    remindLabel.font = SmallDecisionsSetFontSize(11);
    remindLabel.textColor = SmallDecisionsNormalColor;
    remindLabel.text = @"通过用户的iTunes账户扣款，用户确认购买后即付款,苹果iTunes账户会在到期前24小时内扣费，扣费成功后订阅周期顺延1个订阅周期,如需取消订阅，请在当前订阅期结束前至少24小时操作，操作方法：进入系统【设置】—>点击【iTunes Store与App Store】—>点击【Apple ID】—>点击【订阅】，选择取消订阅即可。";
    remindLabel.numberOfLines = 0;
    [self.bottomMaskView addSubview:remindLabel];
    [remindLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(openVipBtn.mas_bottom).offset(32);
        make.right.equalTo(self.view).offset(-20);
        make.left.equalTo(self.view).offset(20);
    }];

    UIButton *privateProtocolBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [privateProtocolBtn setTitle:@"《隐私协议》" forState:UIControlStateNormal];
    [privateProtocolBtn setTitleColor:SmallDecisionsNormalColor forState:UIControlStateNormal];
    [privateProtocolBtn setTitleColor:[UIColor clearColor] forState:UIControlStateHighlighted];
    privateProtocolBtn.titleLabel.font = SmallDecisionsSetFontSize(12);
    [privateProtocolBtn addTarget:self action:@selector(privateProtocolBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomMaskView addSubview:privateProtocolBtn];

    [privateProtocolBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(remindLabel.mas_bottom).offset(32);
        make.right.equalTo(self.view.mas_centerX).offset(-22);
    }];

    UIButton *userProtocolBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [userProtocolBtn setTitle:@"《用户协议》" forState:UIControlStateNormal];
    [userProtocolBtn setTitleColor:SmallDecisionsNormalColor forState:UIControlStateNormal];
    [userProtocolBtn setTitleColor:[UIColor clearColor] forState:UIControlStateHighlighted];
    userProtocolBtn.titleLabel.font = SmallDecisionsSetFontSize(12);
    [userProtocolBtn addTarget:self action:@selector(userProtocolBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomMaskView addSubview:userProtocolBtn];
    [userProtocolBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(privateProtocolBtn);
        make.left.equalTo(self.view.mas_centerX).offset(22);
        make.bottom.equalTo(self.containerScrollView.mas_bottom).offset(-22);
    }];
}

- (UIView *)bottomMaskView {
    if(!_bottomMaskView) {
        _bottomMaskView = [[UIView alloc] init];
        _bottomMaskView.backgroundColor = SmallDecisionsSecondBgColor;
        [self.containerScrollView addSubview:_bottomMaskView];
    }
    return _bottomMaskView;
}

- (void)openVipBtnAction {
    NSDictionary *data = self.vipItems[self.vipItemCheckedIndex];
    weakSelf(self);
    [SmallDecisionsHUDHelper showLoading:@"购买中..." view:self.view];
    [SmallDecisionsIAPHelper applePayIAPWithProductId:data[@"productId"] successBlock:^(NSString * result) {
        [SmallDecisionsHUDHelper hideHUDForView:weakself.view];
        [SmallDecisionsHUDHelper showSuccess:result];
        if(self.callback) {
            self.callback(@{@"result":@(YES)});
        }
    } failedBlock:^(NSString * result) {
        [SmallDecisionsHUDHelper hideHUDForView:weakself.view];
        [SmallDecisionsHUDHelper showSuccess:result];
        if(self.callback) {
            self.callback(nil);
        }
    }];
}

- (void)privateProtocolBtnAction {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"privacyProtocol" ofType:@"html"];
    [self openWebViewControllerWithPath:path];
}

- (void)userProtocolBtnAction {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"userProtocol" ofType:@"html"];
    [self openWebViewControllerWithPath:path];
}

- (void)openWebViewControllerWithPath:(NSString *)path {
    SmallDecisionsWebViewController *webVC = [[SmallDecisionsWebViewController alloc] init];
    webVC.webUrl = [NSURL fileURLWithPath:path];
    [SmallDecisionsNavigatorManager presentViewController:webVC animationType:SmallDecisionsAnimationTypeFullPop];
}

- (UICollectionView *)collectionView {
    if(!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemW = kScreenWidth / 3.0 - 15;
        CGFloat itemH = 142;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        flowLayout.itemSize = CGSizeMake(itemW, itemH);
        flowLayout.minimumInteritemSpacing = 10;
        flowLayout.minimumLineSpacing = 10; // cell 间距

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[SmallDecisionsVipCell class] forCellWithReuseIdentifier:@"SmallDecisionsVipCellId"];
    }
    return  _collectionView;;
}

#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.vipItems.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SmallDecisionsVipCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SmallDecisionsVipCellId" forIndexPath:indexPath];
    NSDictionary *data = self.vipItems[indexPath.item];
    cell.data = data;
    cell.isSelected = self.vipItemCheckedIndex == indexPath.item;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    self.vipItemCheckedIndex = indexPath.item;
    [collectionView reloadData];
}

- (UIScrollView *)containerScrollView {
    if(!_containerScrollView) {
        _containerScrollView = [[UIScrollView alloc] init];
        [self.view addSubview:_containerScrollView];
        [_containerScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.height.equalTo(self.view).offset(0);
        }];
    }
    return _containerScrollView;
}

- (UIView *)setRightBarButton {
    UIButton *recoverBuyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [recoverBuyBtn setTitle:@"恢复购买" forState:UIControlStateNormal];
    recoverBuyBtn.titleLabel.font = SmallDecisionsSetFontSize(13);
    [recoverBuyBtn setTitleColor:SmallDecisionsNormalColor forState:UIControlStateNormal];
    recoverBuyBtn.frame = CGRectMake(0, 0, 30, 30);
    return recoverBuyBtn;
}

- (void)rightBarButtonAction:(UIButton *)view {
    [SmallDecisionsHUDHelper showLoading:@"恢复中..." view:self.view];
    [SmallDecisionsIAPHelper applePayIAPRestoreProductSuccessBlock:^(NSString * result) {
        [SmallDecisionsHUDHelper hideHUDForView:self.view];
        [SmallDecisionsHUDHelper showSuccess:result];
        if(self.callback) {
            self.callback(@{@"result":@(YES)});
        }
    } failedBlock:^(NSString * result) {
        [SmallDecisionsHUDHelper hideHUDForView:self.view];
        [SmallDecisionsHUDHelper showSuccess:result];
        if(self.callback) {
            self.callback(nil);
        }
    }];
}


- (void)setLeftBarButtonItemCloseButton {
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    closeButton.frame = CGRectMake(0, 0, 30, 30);
    [closeButton setImage:[UIImage imageNamed:@"global_close"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(closeButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *closeBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: closeButton];
    self.navigationItem.leftBarButtonItem = closeBarButtonItem;
}

- (void)closeButtonAction {
    [SmallDecisionsNavigatorManager dismissViewControllerAnimated:YES completion:nil];
}


@end
